package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

    private final StringRedisTemplate stringRedisTemplate;
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验手机号
        //如果不符合 返回错误信息
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式错误！");
        }
        //如果符合 生成验证码
        String code = RandomUtil.randomNumbers(6);
        //保存在session中
//        session.setAttribute(SESSION_CODE,code);
        stringRedisTemplate.opsForValue().
                set(LOGIN_CODE_KEY+phone, code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //发送验证码
        log.info("发送短信验证码成功：{}",code);

        return Result.ok();
    }

    @Override
    public Result<String> login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();

        //校验手机号格式
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式错误！");
        }
        //检验验证码是否一致
        String code = loginForm.getCode();
        //验证码不一致 返回错误信息
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if(cacheCode==null||!cacheCode.equals(code)){
            return Result.fail("验证码错误！");
        }
        //验证码一致 查询用户是否存在
        User user = query().eq("phone", phone).one();
        //不存在创建新用户  ，保存用户到数据库 ，
        if(user==null){
            user = createUserWithPhone(phone);
        }
        //随机生成token
        String token = UUID.randomUUID().toString();

        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //将用户信息转换成HashMap存储
        Map<String, Object> map = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor(
                                (fieldName,fieldValue)
                                        ->fieldValue.toString()
                        )
        );
        //将用户信息存入redis
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token,map);
        //设置过期时间
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,LOGIN_USER_TTL,TimeUnit.MINUTES);
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //获取当前登陆的用户
        Long userId = UserHolder.getUser().getId();
        //获取日期
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        //拼接key
        String key=USER_SIGN_KEY+userId+keySuffix;
        //获取今天是本月的第几天
        int day = now.getDayOfMonth()-1;
        stringRedisTemplate.opsForValue().setBit(key,day,true);
        //写入redis

        return Result.ok();
    }

    @Override
    public Result signCount() {
        //获取本月戒指今天为止的所有签到记录
        //获取当前登陆的用户
        Long userId = UserHolder.getUser().getId();
        //获取日期
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        //拼接key
        String key=USER_SIGN_KEY+userId+keySuffix;
        //获取今天是本月的第几天
        int day = now.getDayOfMonth();
        List<Long> list = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(day))
                        .valueAt(0)
        );
        if(list==null||list.isEmpty()){
            return Result.ok(0);
        }
        Long num = list.get(0);
        if(num==null||num==0){
            return Result.ok(0);
        }
        int count=0;

        while ((num & 1) != 0) {
            count++;
            num >>>= 1;
        }

        return Result.ok(count);
    }

    /**
     * 通过电话创建新用户
     * @param phone
     */
    private User createUserWithPhone(String phone) {
        User user = User
                .builder()
                .phone(phone)
                .nickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(10))
                .build();
        save(user);
        return user;
    }
}
